﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using JwtAuthorizationSample.Models;
using JwtAuthorizationSample.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthorizationSample.Controllers
{
    [Route("api/[controller]/[action]")]
    public class AuthorizeController : Controller
    {
        private readonly IOptions<JwtSettings> _optionAccessor;
        public AuthorizeController(IOptions<JwtSettings> optionAccessor)
        {
            this._optionAccessor = optionAccessor;
        }
        [HttpPost]
        public IActionResult CreateToken(LoginVm vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var claims = new List<Claim>() { new Claim(ClaimTypes.Name, "Zj"), new Claim(ClaimTypes.Role, "admin") };
            var jwtSettings = _optionAccessor.Value;
            var credentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                jwtSettings.Issuer,
                jwtSettings.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(30),
                credentials);
            return Json(new { Token= new JwtSecurityTokenHandler().WriteToken(jwtToken) });
        }
    }
}